package com.wanlian.router;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.smart.android.ui.BaseActivity;
import com.smart.android.utils.ActivityStackManager;
import com.wanlian.router.bean.MessageCount;
import com.wanlian.router.bean.User;
import com.wanlian.router.event.LogOut;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.UploadServer;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.ui.login.LoginActivity;
import com.wanlian.router.ui.main.HomeFragment;
import com.wanlian.router.ui.main.YunFilesActivity;
import com.wanlian.router.ui.manage.ManageFragment;
import com.wanlian.router.ui.me.MineFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends BaseActivity {
    private static final String SAVETABID = "saveTabId";
    private HomeFragment mHomeFragment;
    private MineFragment mMineFragment;
    private ManageFragment mManageFragment;

    private Fragment mCurrentShowFragment;
    private int saveTabId = 0;

    @BindView(R.id.tv_home)
    TextView home;
    @BindView(R.id.tv_manage)
    TextView manage;
    @BindView(R.id.tv_mine)
    TextView mine;

    private Badge mQBadgeView;

    @Override
    protected int layout() {
        return R.layout.activity_main;
    }

    @Override
    public void initUI() {
        super.initUI();
    }

    @Override
    public void initData() {
        super.initData();
//        new UpgradeDialog(getActivity()).show();
//        new DeleteDialog(getActivity()).show();

        if (GlobalInfo.getInstance().getUser()!=null) {
            User u = GlobalInfo.getInstance().getUser();
            if (TextUtils.isEmpty(u.getUserTag())) {
                return;
            }
            JPushInterface.setAlias(getApplicationContext(), (int) u.getId(), u.getUserTag());
        }


        startService(new Intent(this, UploadServer.class));
    }

    private void messageCount(int count) {
        if (mQBadgeView == null) {
            mQBadgeView = new QBadgeView(this)
                    .bindTarget(mine)
                    .setGravityOffset(45, 2, true)
                    .setBadgeTextSize(0.1f, true);
        }
        mQBadgeView.setBadgeNumber(count > 0 ? -1 : 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (savedInstanceState != null) {
            mHomeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag(HomeFragment.class.getName());
            mManageFragment = (ManageFragment) getSupportFragmentManager().findFragmentByTag(ManageFragment.class.getName());
            mMineFragment = (MineFragment) getSupportFragmentManager().findFragmentByTag(MineFragment.class.getName());
            saveTabId = savedInstanceState.getInt(SAVETABID, 0);
        }

        switch (saveTabId) {
            case 0:
                showHome();
                break;
            case 1:
                showManage();
                break;
            case 2:
                showMine();
                break;
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SAVETABID, saveTabId);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void showHome() {
        mine.setSelected(false);
        manage.setSelected(false);
        home.setSelected(true);
        if (mHomeFragment == null) {
            mHomeFragment = HomeFragment.newInstance();
        }

        if (mHomeFragment.equals(mCurrentShowFragment)) {
            return;
        }
        showFragment(mHomeFragment);
    }

    private void showManage() {
        mine.setSelected(false);
        manage.setSelected(true);
        home.setSelected(false);
        if (mManageFragment == null) {
            mManageFragment = ManageFragment.newInstance();
        }

        if (mManageFragment.equals(mCurrentShowFragment)) {
            return;
        }
        showFragment(mManageFragment);
    }

    private void showMine() {
        mine.setSelected(true);
        manage.setSelected(false);
        home.setSelected(false);
        if (mMineFragment == null) {
            mMineFragment = MineFragment.newInstance();
        }

        if (mMineFragment.equals(mCurrentShowFragment)) {
            return;
        }
        showFragment(mMineFragment);
    }

    private void showFragment(Fragment show) {
        FragmentTransaction ft = getSupportFragmentManager()
                .beginTransaction();

        if (!show.isAdded()) {
            ft.add(R.id.fragment, show, show.getClass().getName());
        }

        if (mCurrentShowFragment != null
                && mCurrentShowFragment.isAdded()
                && !mCurrentShowFragment.isHidden()) {
            ft.hide(mCurrentShowFragment);
        }

        if (show.isHidden()) {
            ft.show(show);
        }
        ft.commit();
        mCurrentShowFragment = show;
    }


    @OnClick(R.id.tv_home)
    void home(TextView v) {
        v.setSelected(true);
        showHome();

    }

    @OnClick(R.id.tv_manage)
    void manage(TextView v) {
        v.setSelected(true);
        showManage();

        home.setSelected(false);
        mine.setSelected(false);
    }

    @OnClick(R.id.tv_mine)
    void mine(TextView v) {
        v.setSelected(true);
        showMine();

        home.setSelected(false);
        manage.setSelected(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogout(LogOut logOut) {
        if (GlobalInfo.getInstance().isLogin()) {
            GlobalInfo.getInstance().logout();

            new AlertDialog.Builder(ActivityStackManager.getInstance().currentActivity())
                    .setMessage("你已退出登录，请重新登录")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            redirectActivity(LoginActivity.class);
                            ActivityStackManager.getInstance().finishAllActivityExcept(LoginActivity.class);
                        }
                    }).create().show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        NetWorkingClient.getInstance().queryMessageCount(getActivity(), new INetCallBack<MessageCount>() {
            @Override
            public void onFinish(ResponseData response, @Nullable MessageCount messageCount) {
                if (response.isSuccess()) {
                    if (messageCount != null) {
                        messageCount(messageCount.getCount());
                    }else {
                        messageCount(0);
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
